import { ElMessage } from "element-plus";

// 定义WebSocket的类型
let socket: WebSocket | null = null;
let interval: number = 0;
const event = new Map<string, Function>(); // 用于事件缓存，key是事件类型，value是回调函数

// 定义返回数据的接口
interface WebSocketData {
    code: string;
    data: any;
}

function open(): Promise<void> {
    return new Promise((resolve, reject) => {
        if (socket) {
            resolve();
            return;
        }

        const host = location.host;
        const href = location.href;
        const baseUrl = `${/^https:\/\//.test(href) ? 'wss://' : 'ws://'}${host}`;
        const url = `${baseUrl}/api/websocket/meeting`;
        socket = new WebSocket(url);

        // 保持socket不被掐掉，如果socket过一段时间不发消息就会自动断开连接
        socket.onopen = () => {
            // interval = setInterval(() => {
            //     if (socket && socket.readyState === WebSocket.OPEN) {
            //         const message = JSON.stringify({
            //             code: 'PING',
            //             data: {},
            //         });
            //         socket.send(message);
            //     }
            // }, 1000 * 10);
            resolve();
        };

        socket.onmessage = (e: MessageEvent) => {
            const res: string = e.data;
            if (res) {
                const { code, data }: WebSocketData = JSON.parse(res);
                handleResult(code, data);
                if (code === 'CONNECT_SUCCESS') {
                    console.log('连接成功id', data);
                    (socket as WebSocket & { uuid: string }).uuid = data;
                }
            }
        };

        socket.onclose = (e: CloseEvent) => {
            clearInterval(interval);
            ElMessage('断开连接');
            socket = null;
            console.error(e);
        };

        socket.onerror = (e: Event) => {
            ElMessage.error('连接出问题');
            console.error((e as ErrorEvent).message);
        };
    });
}

function close(): void {
    socket?.close();
}

function send(code: string, data: any): void {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ code, data }));
    }
}

// 处理返回结果
function handleResult(code: string, data: any): void {
    const callback = event.get(code);
    if (typeof callback === 'function') {
        callback(data);
    }
}

// 做事件的缓存
function addEventHandler(key: string, callback: Function): void {
    event.set(key, callback);
}

function removeEventHandler(key: string): void {
    event.delete(key);
}

export default {
    open,
    close,
    send,
    addEventHandler,
    removeEventHandler,
};
